package drtySyntaxEditor.actions;

import javax.swing.text.BadLocationException;

import drtySyntaxEditor.DrtySyntaxEditor;

public class ActionUtils {
	
	/**
	 * Looks at the selection start and end of the editor (Can be the same if nothing 
	 * is selected) and determines the beginning position of the first selected line 
	 * and the end position of the last selected line.
	 * 
	 * @param ed The DrtySyntaxEditor object on which we want to perform the function
	 * @return int array containing the start position of the first selected line and
	 * end position of the last selected line.
	 */
	public static int[] getSelectedLinesRange(DrtySyntaxEditor ed) {
		int [] ret = new int[0];
		//ret[0] = -1;
		//ret[1] = -1;
		
		try {
			int selStart = ed.getSelectionStart();
			int selEnd = ed.getSelectionEnd();
			int txtLen = ed.getText().length();
			String lineSep = System.getProperty("line.separator");
			
			//System.out.println("--\nStart " + selStart);
			//System.out.println("End " + selEnd);
	
			// Don't bother if there is no content.
			if (txtLen > 0) {
				
				// If the selStart is the end of a line already
				if (ed.getText(selStart, 1).equals(lineSep)) {
					selStart -= 1;
				}
				
				// Get the beginning of the line of the selStart
				while (selStart >= 0) {
					//System.out.print(selStart + ",");
					if (ed.getText(selStart, 1).equals(lineSep)) {
						break;
					}
					selStart --;
				}
				// When the loop above breaks or ends selStart will be out of bounds or refer to a lineSep
				// So just add 1 to it to refer to the first char or the beginning char of the line.
				selStart++;
				
				// Get the end of the line of selEnd.
				while (selEnd < txtLen){
					if (ed.getText(selEnd, 1).equals(lineSep)) {
						break;
					}
					selEnd++;
				}
				
				
				//System.out.println("New Start " + selStart);
				//System.out.println("New End " + selEnd);
				//System.out.println("Length " + txtLen);
				//ed.select(selStart, selEnd);
				
				ret = new int[2];
				ret[0] = selStart;
				ret[1] = selEnd;
			}
			else {
				// There is no content, so the beginning and end of the line is 0.
				ret = new int[2];
				ret[0] = 0;
				ret[1] = 0;
			}
		}
		catch (BadLocationException ex) {
			// Bad location somewhere when using ed.getText(off, len)
			ex.printStackTrace();
		}
		
		return ret;
	}
}
